
class Unit extends egret.Bitmap{
	public static SIZE:number = 32;

	public static R:number = 0xff0000;
	public static G:number = 0x00ff00;
	public static B:number = 0x0000ff;

	static colorList:Array<number>;

	static pool:Object = {};
	public static create(colorType:number):Unit{
		let result:Unit;
		if(Unit.pool[colorType] && Unit.pool[colorType].length > 0){
			result = Unit.pool[colorType].shift();
		}else{
			result = new Unit(colorType);
		}
		return result;
	}

	static t:egret.Texture;
	static getTexture():egret.Texture{
		if(Unit.t != null){
			return Unit.t;
		}
		if(Unit.colorList == null){
			Unit.colorList = [0,Unit.R,Unit.G,Unit.B];
		}
		let s:egret.Shape = new egret.Shape();
		let i:number = 0;
		for( let c of Unit.colorList){
			s.graphics.beginFill(c);
			s.graphics.drawRect(i * GRID_SIZE,0,GRID_SIZE,GRID_SIZE);
			i++;
		}
		s.graphics.endFill();
		Unit.t = new egret.RenderTexture();
		(Unit.t as egret.RenderTexture).drawToTexture(s);
		return Unit.t;
	}

	public gx:number = 0;
	public gy:number = 0;
	public colorType:number = 0;

	public constructor(colorType:number){
		super();
		this.fillMode = egret.BitmapFillMode.CLIP;
		this.colorType = colorType;
		let t:egret.Texture = Unit.getTexture();

		let tt:egret.Texture = new egret.Texture();
		tt.bitmapData = t.bitmapData;
		tt._bitmapX = colorType * GRID_SIZE;
		this.texture = tt;
		//this.texture = t;
		this.width = GRID_SIZE;
		this.height = GRID_SIZE;
	}

	public reset(gx:number,gy:number):void{
		this.gx = gx;
		this.gy = gy;
		this.x = gx * GRID_SIZE;
		this.y = gy * GRID_SIZE;
	}

	public destroy():void{
		if(this.parent != null){
			this.parent.removeChild(this);
		}
		this.gx = 0;
		this.gy = 0;
		if(Unit.pool[this.colorType] == null){
			Unit.pool[this.colorType] = [];
		}
		Unit.pool[this.colorType].push(this);
	}
}
